package com.cy.bfzcommons.web.util.jwt;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    public static final String SECRET = "123456ABC";
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 30;

    public static String createToken(Long userId){                          //加密
        Date iatDate = new Date();                                          //获取当前时间
        Calendar instance = Calendar.getInstance();
        instance.add(calendarField,calendarInterval);
        Date expiresDate = instance.getTime();                              //获取到期时间
        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");                                             //添加加密模式
        map.put("typ","JWT");                                               //返回类型

        String token = JWT.create().withHeader(map)
                .withClaim("userId",userId)
                .withIssuedAt(iatDate)
                .withExpiresAt(expiresDate)
                    .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static Map<String, Claim> verifyToke(String token){              //校验
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt  = verifier.verify(token);
        } catch (JWTVerificationException e) {
//            e.printStackTrace();
            throw new  RuntimeException("校验失败");
        }
        return jwt.getClaims();
    }

    public static Long getuserId(String token){
        Map<String, Claim> map = verifyToke(token);
        Claim userId = map.get("userId");

        if(userId.asLong()==null){
            throw new RuntimeException("验证出错");
        }
        return userId.asLong();
    }

}
